package com.kaishengit.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.ResultTransformer;
import org.springframework.stereotype.Repository;

import com.kaishengit.dao.core.BaseDao;
import com.kaishengit.dao.core.Page;
import com.kaishengit.pojo.Message;
import com.kaishengit.pojo.User;

@Repository
public class MessageDao extends BaseDao<Message,Integer>{

	@SuppressWarnings("unchecked")
	public Page<Message> findAllByForeignObject(User user,Page<Message> page) {
		Criteria cri = getSession().createCriteria(Message.class);
		cri.add(Restrictions.eq("user", user));
		cri.setFirstResult(page.getOffSet());
		cri.setMaxResults(page.getPageSize());
		cri.addOrder(Order.desc("id"));
		List<Message> list = cri.list();
		page.setResult(list);
		return page;
	}

	public long findTotalCount(User user) {
		Criteria c = getSession().createCriteria(Message.class);
		c.add(Restrictions.eq("user", user));
		ResultTransformer t = c.ROOT_ENTITY;
		
		c.setProjection(Projections.rowCount());
		Long result =  (Long) c.uniqueResult();
		
		c.setProjection(null);
		c.setResultTransformer(t);
		
		return result != null ? result : 0;
	}

}
